<template>
  <div >
    <div style="margin: -14px 0px 0px; padding: 2px 0px">
      <a-card :bordered="false">
        <a-form>
          <a-row :gutter="12">
            <a-col :md="6">
               
              <div class="package-search-box">
                <span style="width:100px;">套餐名称：</span> 
                <a-input v-model.trim="searchDB.packageName" allow-clear placeholder="请输入套餐名称" @keydown.enter="search"></a-input>
              </div>
            </a-col> 
            <a-col :md="6">
              <div style="display: flex; align-items: center;padding-right:10px;">
                <span style="width: 100px">登记时间:</span>
                <a-range-picker :allowClear="true"  v-model="day" style="width: 100%" @calendarChange="tests">
                  <a-icon slot="suffixIcon" type="calendar" />
                </a-range-picker>
              </div>
            </a-col>
            <a-col :md="5" :sm="24" >
              <div class="package-search-box">
                <span style="width: 80px">启用状态：</span>
                <!-- <a-switch @change="isDisabledChange" />  -->
                <a-select  
                  class="package-search-box-input"
                  placeholder="请选择"
                  allowClear 
                  v-model.trim="searchDB.isDisabled"
                >
                  <a-select-option :value="undefined">
                    <div>请选择</div>
                  </a-select-option>
                  <a-select-option :value="0">
                    <div>已启用</div>
                  </a-select-option>
                  <a-select-option :value="1">
                    <div>未启用</div>
                  </a-select-option>
                </a-select>
              </div> 
            </a-col>
            
            <a-col :md="7">
              <div>
                <a-button type="primary" style="margin: 0 10px" @click="search('search','one')">搜索</a-button>
                <a-button @click="reset">重置</a-button>
              </div>
            </a-col>
          </a-row>
          <a-row :gutter="12">
            <a-col :md="5" :sm="24" >
              <div class="package-search-box" style="margin-bottom:0px;">
                <span style="width: 80px">过期状态：</span>
                <!-- <a-switch @change="isDisabledChange" />  -->
                <a-select  
                  class="package-search-box-input"
                  placeholder="请选择"
                  allowClear 
                  v-model.trim="searchDB.overdueDate"
                >
                  <a-select-option :value="undefined">
                    <div>请选择</div>
                  </a-select-option>
                  <a-select-option :value="2">
                    <div>已过期</div>
                  </a-select-option>
                  <a-select-option :value="1">
                    <div>未过期</div>
                  </a-select-option>
                </a-select>
              </div> 
            </a-col>
            <a-col :md="5" :sm="24" >
              <div class="package-search-box" style="margin-bottom:0px;">
                <span style="width: 80px">套餐类型：</span>
                <!-- <a-switch @change="isDisabledChange" />  -->
                <a-select  
                  class="package-search-box-input"
                  placeholder="请选择"
                  allowClear 
                  v-model.trim="searchDB.ptype"
                >
                  <a-select-option :value="undefined">
                    <div>请选择</div>
                  </a-select-option>
                  <a-select-option :value="1">
                    <div>长期套餐</div>
                  </a-select-option>
                  <a-select-option :value="2">
                    <div>当月套餐</div>
                  </a-select-option>
                </a-select>
              </div> 
            </a-col>
            <a-col :md="9" :sm="24" style="padding-right:0;">
              <div class="package-search-box" style="margin-bottom:0px;">
                <span style="width: 80px">价格区间:</span>
                <a-input-number
                  :min="1" 
                  :default-value="0" 
                  :value="searchDB.minPrice"
                  :formatter="value => `${value}`"
                  :parser="value => value.replace(/\$\s?|(,*)/g, '')"  
                  @change="value => {  
                    if(!isNumber(value)){
                      this.searchDB.minPrice = undefined
                    }else{
                      this.searchDB.minPrice = Number(value)
                      this.searchDB = Object.assign({},this.searchDB)
                    } 
                  }"
                />
                -
                <a-input-number
                  :default-value="0" 
                  :value="searchDB.maxPrice"
                  :min="searchDB.minPrice" 
                  :formatter="value => `${value}`"
                  :parser="value => value.replace('%', '')"  
                  @change="value => {  
                    if(!isNumber(value)){
                      this.searchDB.maxPrice = undefined
                    }else{
                      this.searchDB.maxPrice = Number(value)
                      this.searchDB = Object.assign({},this.searchDB)
                    } 
                  }"
                />
              </div> 
            </a-col> 
            
          </a-row>
        </a-form>
      </a-card>
    </div>
    <div style="margin: 8px 0px; padding: 2px 0px">
      <a-card :bordered="false" style="display: flex; flex-direction: column">
        <a-button type="primary" style="border-radius: 50px; margin: 10px" @click="add('1')">新增套餐</a-button>
        <a-table 
          @expand="ca"
          @change="handleTableChange"
          :expanded-row-keys="ExpandedRowKeys"
          :columns="columns"  
          :data-source="data"
          :loading="loading"
          :pagination="pagination"
          :rowKey="(record) => record.tbPackageId"
          class="components-table-demo-nested"
        >
          <a slot="operation" slot-scope="text, record">
            <span @click="add('2', record)">修改</span>
            <!-- <span style="margin: 0 10px">复制</span> -->
          </a>
          <span slot="tags" slot-scope="tags">
            <a-tag :color="tags === '已启用' ? '#39f' : tags === '未过期' ? 'green' : '#d9d9d9'">
              {{ tags }}
            </a-tag>
          </span>
          <span slot="subTags" slot-scope="subTags">
            <a-tag :color="subTags === '已启用' ? '#39f' : subTags === '未过期' ? 'green' : '#d9d9d9'">
              {{ subTags }}
            </a-tag>
          </span>
          <a-table
            slot="expandedRowRender"
            
            id="innerTable"
            :columns="innerColumns"
            :data-source="innerData"
            :loading="openLoading"
            :pagination="false"
            :rowKey="(record, index) => record.itemId + index"
          >
            <template slot="footer" >
              <div v-if="loadMore" @click="loadMores">
                <a-button type="primary"  style="width: 300px; border: 1px solid #e1e2e3;margin: 0 auto;display: block;">加 载 更 多</a-button>
              </div>
            </template>
            <span slot="abled" slot-scope="abled">
              <a-tag :color="abled === '已启用' ? '#39f' : '#d9d9d9'">
                {{ abled }}
              </a-tag>
            </span> 
            <span slot="operation" class="table-operation">
              <a>删除</a>
            </span>
          </a-table>
        </a-table>
      </a-card>
    </div>

    <!--弹框-->
    <a-modal title="套餐设置" :visible="visible" @ok="handleOk" @cancel="handleCancel">
      <a-form :form="form">
        <a-form-item  style="margin-bottom:0px;">
          <a-row :gutter="24">
            <a-col :span="6">
              <div class="searchItem">
                <a-form-item label="套餐名称" class="formItem" style="margin-bottom:10px;">
                  <a-input
                    style="width: 200px"
                    placeholder="请输入套餐名称"
                    v-decorator="['packageName', { rules: [{ required: true, message: '请输入！' }] }]"
                  ></a-input>
                </a-form-item></div
            ></a-col>
            <a-col :span="5">
              <div class="searchItem" style="margin: 0 2px">
                <a-form-item label="套餐类型" class="formItem" style="margin-bottom:10px;">
                  <a-select
                    style="width: 150px"
                    @change="handleChange"
                    v-decorator="['ptype', { rules: [{ required: true, message: '请输入！' }] }]"
                  >
                    <a-select-option v-for="item in isType" :key="item.id" :isdisabled="item.label" :value="item.label">
                      <div>{{ item.value }}</div>
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </div>
            </a-col>
            <a-col :span="9">
              <div style="display: flex">
                <a-form-item label="登记时间" class="formItem" style="margin-bottom:10px;"> 
                  <a-range-picker
                    v-decorator="['registDate', { rules: [{ required: true, message: '请输入！' }] }]"
                    style="width: 100%"
                  >
                    <a-icon slot="suffixIcon" type="calendar" />
                  </a-range-picker>
                </a-form-item>
              </div>
            </a-col>
            <a-col :md="4" :sm="24">
              <a-form-item label="启用状态" class="formItem" style="margin-bottom:10px;">
                <a-switch
                  v-decorator="['isDisabled', { valuePropName: 'checked', rules: [{ required: false, message: '请输入！' }] }]"
                
                ></a-switch>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form-item>
        <a-form-item label="备注" style="margin-bottom:10px;">
          <a-row :gutter="48">
            <a-col :span="12">
              <a-textarea
                placeholder="请填写备注"
                v-decorator="['remark', { rules: [{ required: true, message: '请输入！' }] }]"
              />
            </a-col>
          </a-row>
        </a-form-item> 
        
        
        <a-form-item label="选择明细" style="margin-bottom: 10px;">
          <a-popover placement="right" v-model="ShowPopover" trigger="click">
            <a slot="content" @click="hide" style="display: flex">
              <span style="margin-left: auto">×</span>
            </a>
            <template slot="content" class="box-content-div">
              <a-row :gutter="24">
                <!-- <a-col :span="8">
                  <div class="searchItem" style="margin: 10px 0">
                    <span>拼音码</span><a-input placeholder="请输入"></a-input>
                  </div>
                </a-col> -->
                <a-col :span="15">
                  <div class="searchItem" style="margin: 10px 0">
                    <span style="width:44px">名称：</span
                    ><a-input style="width:auto !important;" allow-clear placeholder="请输入产品或项目名称" v-model.trim="name" @keydown.enter.native="send"></a-input>
                  </div>
                </a-col>
                <!-- <a-button @click="send">test</a-button> -->
                <a-col :span="9" style="line-height: 49px;">
                  <div style="display: flex; align-items: center">
                    <span
                      >数据来源：
                      <a-switch
                        style="margin-left:5px;margin-top: -6px;"
                        checked-children="项目"
                        un-checked-children="产品"
                        v-model="typeState"
                        @change="getType"
                      ></a-switch
                    ></span>
                  </div>
                </a-col>
              </a-row>

              <a-table
                :columns="detaiColumns"
                :customRow="clicks"
                :data-source="detailed"
                :rowKey="(record, index) => index"
                :loading="detailLoading"
                :pagination="typepagination"
                @change="typeChange" 
              >
                <a slot="name" slot-scope="text">{{ text }}</a>  
              </a-table>
            </template>
            <a-button type="primary">新增</a-button>
          </a-popover>
        </a-form-item>
        <a-form-item>
          <a-table
            ref="set"
            
            :columns="columnsSet"
            :data-source="packageDetail"
            :pagination="false"
            :loading="addpackageLoading"
            :rowKey="
              (record,idx) => {
                return record.itemId + idx
              }
            "
            class="add-table-style"
          >
            
            <template slot="originalPrice" slot-scope="text, record">
               {{text && (Number(text) / Number(record.times)).toFixed('2')}}
            </template>
            <template slot="useTimes" slot-scope="text, record, index">
              <a-input-number placeholder="请输入数量" :min="1" :value="text" @change="value => textChange2(value,record,index)"></a-input-number>
            </template>
            <template slot="amt" slot-scope="text, record, index">
              <a-input-number placeholder="请输入套餐价" :min="0" :value="text" @change="value => textChange(value,record,index)"></a-input-number>
            </template>
            <span slot="operation" slot-scope="text, record, index" class="table-operation">
              <!-- <a @click="removeItem(record)">删除</a> -->
              <a-popconfirm title="删除该项数据?" @confirm="() => removeItem(record, index)">
                <a>删除</a>
                <!-- <a href="javascript:;">Delete</a> -->
              </a-popconfirm>
            </span>
            <template slot="footer" >
              <div class="footer-box-style">
                <div style="display: inline-flex; align-items: center;width: 100%;border-bottom: 1px solid #e2e2e2;">
                  <span style="margin: 0 10px">
                    合计金额：<span style="color: red;font-size: 17px;font-weight: bold; margin: 0 5px"><i>¥</i> {{ TotalitemNoPrice + TotalProductNoPrice }}</span>
                  </span>
                </div>
                <br />
                <span style="margin: 0 10px"
                  >项目个数：<span style="color: #3399ff;font-size: 17px;font-weight: bold; margin: 0 5px">{{ TotalitemNo }}</span></span
                > 
                <span style="margin: 0 10px"
                  >项目金额：<span style="color: red;font-size: 17px;font-weight: bold; margin: 0 5px"><i>¥</i> {{ TotalitemNoPrice }}</span></span
                >
                <br />
                <span style="margin: 0 10px"
                  >产品个数：<span style="color: #3399ff;font-size: 17px;font-weight: bold; margin: 0 5px">{{ TotalProductNo }}</span></span
                >
                <span style="margin: 0 10px"
                  >产品金额：<span style="color: red;font-size: 17px;font-weight: bold; margin: 0 5px"><i>¥</i> {{ TotalProductNoPrice }}</span></span
                >
              </div>
            </template>
          </a-table>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
  /**f0faff */
  /deep/ .ant-modal {
    width: 1280px !important;
  }
  .formItem {
    display: inline-flex !important;
  }
  /deep/ .ant-modal {
    width: 999px;
  }
  /deep/ .ant-popover-inner-content {
    width: 500px !important;
  }
  .searchItem {
    display: flex;
    align-items: center;
  }
  .searchItem span {
    width: 100px;
  }
  /deep/ #innerTable .ant-table-thead {
    background-color: #f0faff !important;
  }
  /deep/ #innerTable .ant-table-thead > tr > th {
    background: none !important;
  }
  /deep/ .ant-table-expanded-row > td:first-child {
    display: none !important;
  }
  /* /deep/ .ant-table-expanded-row .ant-table-footer {
    display: none !important;
  } */
  /deep/ .add-table-style .ant-table-footer{
    display:flex;
    padding: 8px 16px;
  }
  /deep/ .add-table-style .ant-table-tbody > tr > td{
    padding: 10px 16px !important;
  }
  .footer-box-style{
    text-align: left;
    margin-left: auto;
    line-height: 29px;
    font-size: 13px;
  } 
  .package-search-box{
    display: flex;
    line-height: 30px;
    margin-bottom: 24px;
    padding-right: 10px;
  }
  .package-search-box .package-search-box-input{
    width: calc(100% - 90px); 
  }
  /* .box-content-div{
    margin: 12px 5px;
  } */
</style>
<script>
const columns = [
  { title: '套餐名称', width:150, align: 'center', dataIndex: 'packageName', key: 'packageName', ellipsis: true },
  {
    title: '启用状态',
    align: 'center',
    // width: 100,
    key: 'tags',
    dataIndex: 'tags',
    align: 'center',

    scopedSlots: { customRender: 'tags' },
  },
  {
    title: '过期状态',
    align: 'center',
    // width: 100,
    key: 'subTags',
    dataIndex: 'subTags',
    align: 'center',
    scopedSlots: {
      customRender: 'subTags',
    },
  },
  // {
  //   title: '启用状态',
  //   dataIndex: 'isDisabled',
  //   key: 'isDisabled',
  //   // customRender: (isDisabled) => {
  //   //   return isDisabled === '0' ? '已禁用' : '已启用'
  //   // },
  //   scopedSlots: { customRender: 'isDisabled' },
  // },
  {
    title: '开始时间',
    align: 'center',
    // width: 120,
    dataIndex: 'beginDate',
    key: 'beginDate',
    customRender: (beginDate) => {
      return beginDate.length > 0 ? beginDate : '-'
    },
  },
  {
    title: '结束时间',
    align: 'center',
    // width: 120,
    dataIndex: 'endDate',
    key: 'endDate',
    customRender: (endDate) => {
      if (!endDate) {
        return '-'
      } else {
        return endDate
      }
    },
  },
  // {
  //   title: '套餐价格',
  //   dataIndex: 'price',
  //   key: 'price',
  //   customRender: (price) => {
  //     if (!price) {
  //       return '-'
  //     } else {
  //       return price
  //     }
  //   },
  // },
  {
    title: '创建人',
    align: 'center',
    // width: 120,
    dataIndex: 'recorder',
    key: 'recorder',
    customRender: (recorder) => {
      if (!recorder) {
        return '-'
      } else {
        return recorder
      }
    },
  },
  {
    title: '创建时间',
    align: 'center',
    // width: 120,
    dataIndex: 'recordDate',
    key: 'recordDate',
    customRender: (recordDate) => {
      if (!recordDate) {
        return '-'
      } else {
        return recordDate
      }
    },
  },
  {
    title: '修改人',
    align: 'center',
    // width: 120,
    dataIndex: 'modifier',
    key: 'modifier',
    customRender: (modifier) => {
      if (!modifier) {
        return '-'
      } else {
        return modifier
      }
    },
  },
  {
    title: '修改时间',
    align: 'center',
    // width: 120,
    dataIndex: 'modifyDate',
    key: 'modifyDate',
    customRender: (modifyDate) => {
      if (!modifyDate) {
        return '-'
      } else {
        return modifyDate
      }
    },
  },
  {
    title: '套餐类型',
    align: 'center',
    // width: 120,
    dataIndex: 'ptype',
    key: 'ptype',
    customRender: (ptype) => {
      return ptype === '1' ? '长期套餐' : '当月套餐'
    },
  },
  {
    title: '套餐价',
    align: 'center',
    // width: 120,
    dataIndex: 'price',
    key: 'price',
    customRender: (price) => {
      if(price == null){
        return '-'
      }else{
        return price.toFixed('2') 
      }
    },
  },
  {
    title: '备注',
    align: 'center',
    // width: 200,
    dataIndex: 'remark',
    key: 'remark',
    ellipsis: true,
    customRender: (remark) => {
      if (!remark) {
        return '-'
      } else {
        return remark
      }
    },
  },
  { 
    title: '操作',
    // width: 80, 
    key: 'operation', 
    scopedSlots: { customRender: 'operation' },
    // fixed: 'right' 
  },
]

const innerColumns = [
  {
    title: '名称',
    align: 'center',
    dataIndex: 'itemName',
    key: 'itemName',
    ellipsis: true,
    width: 300,
    customRender: (itemName) => {
      if (!itemName) {
        return '-'
      } else {
        return itemName
      }
    },
  },
  {
    title: '执行科室',
    align: 'center',
    dataIndex: 'execDeptName',
    key: 'execDeptName',
    customRender: (execDeptName) => {
      if (!execDeptName) {
        return '-'
      } else {
        return execDeptName
      }
    },
  },
  {
    title: '数量',
    align: 'center',
    dataIndex: 'itemTimes',
    key: 'itemTimes',
    customRender: (itemTimes) => {
      if (!itemTimes) {
        return '-'
      } else {
        return itemTimes
      }
    },
  },
  {
    title: '单位',
    align: 'center',
    dataIndex: 'itemUnit',
    key: 'itemUnit',
    customRender: (itemUnit) => {
      if (!itemUnit) {
        return '-'
      } else {
        return itemUnit
      }
    },
  },
  {
    title: '原单价',
    align: 'center',
    dataIndex: 'unitPrice',
    key: 'unitPrice',
    customRender: (unitPrice) => { 
      if (!unitPrice || unitPrice.toString() === 'null') {
        return '-'
      } else {
        return unitPrice
      }
    },
  },
  {
    title: '原总价',
    align: 'center',
    dataIndex: 'totalPrice',
    key: 'totalPrice',
    customRender: (totalPrice) => {
      if (!totalPrice) {
        return '-'
      } else {
        return totalPrice.toFixed('2')
      }
    },
  },
  {
    title: '套餐金额',
    align: 'center',
    dataIndex: 'packagePrice',
    key: 'packagePrice',
    customRender: (packagePrice) => {
      if (!packagePrice) {
        return '-'
      } else {
        return packagePrice.toFixed('2')
      }
    },
  },
  {
    title: '启用状态',
    align: 'center',
    key: 'abled',
    dataIndex: 'abled',
    scopedSlots: {
      customRender: 'abled',
    },
  },
]
const innerData = []

import moment from 'moment'
import { axios } from '@/utils/request'
import { getItemDetailById } from '@/api/modular/main/customer/customerScene'
import { SuperTable, XCard, XDown } from '@/components'
import {
  getPackage,
  getrPackageDetail,
  getPackageDetailList,
  addPackage,
  editDetail,
  editPackage,
  removeItem,
  search,
  searchType,
} from '@/api/bd/package'
export default {
  watch: {
    packageDetail() {
      if(this.packageDetail < 1){
        this.TotalitemNo = 0
        this.TotalitemNoPrice = 0
        this.TotalProductNo = 0
        this.TotalProductNoPrice = 0
      }
      console.log(this.packageDetail)
      this.packageDetail.forEach((item) => {
        // 1 项目 2产品 
        let newData1 = this.packageDetail.filter(elem => {
          return elem.type == 1
        })
        this.TotalitemNo = newData1.length 
        let sumCount = 0
        newData1.map(elem => {
          sumCount+=elem.amt 
        })
        this.TotalitemNoPrice = sumCount 
        let newData2 = this.packageDetail.filter(elem => {
          return elem.type == 2
        })
        this.TotalProductNo = newData2.length
        let sumCount2 = 0
        newData2.map(elem => {
          sumCount2+=elem.amt 
        })
        this.TotalProductNoPrice = sumCount2 
         
        // if (this.packageDetail && this.packageDetail.length > 0) {
        //   this.TotalProject = this.packageDetail.length
        //   this.TotalPrice = this.packageDetail.map((item) => item.amt).reduce((a, b) => a + b)
        // } else {
        // this.productPrince = '0'
        // this.itemPrince = '0'
        // this.TotalitemNo = '0'
        // this.TotalProductNo = '0'
      })
    },
    ShowPopover() {
      if (this.ShowPopover) {
        this.typeState = false
        this.getType(this.typeState)
      }
    },
    'searchDB.packageName': {
      handler: function () {
        this.queryParams.pageNum = 1
        this.queryParams.pageSize = 20
      },
    },
    type(){
      console.log('改变')
      this.typeQueryParam.pageNum = 1
      this.typepagination.current = 1
      this.typeQueryParam.pageSize = 10
    },
    data(){
      this.$nextTick(() => {
        let target = document.getElementsByClassName('ant-table-expanded-row')
        for (var i = 0; i < target.length; i++) {
          target[i].childNodes[1].colSpan = 14
        }
      })
    }
  },
  data() {
    return {
      
      loadMore: false,
      type: '',
      name: '',
      typepagination: {
        total: 0,
        current:1,
        pageSize: 10, //每页中显示10条数据
        // showSizeChanger: true,
        // pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
      },
      innerPagination: {
        total: 0,
        pageSize: 20, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
      },
      pagination: {
        current:1,
        type: '',
        total: 0,
        pageSize: 20, //每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据`, //分页中显示总的数据
      },
      queryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      typeQueryParam:{
        pageNum: 1,
        pageSize: 10,
      },

      Rrecord: {},
      typeState: true,
      detailLoading: false,
      day: [],
      searchDB: {
        start: undefined,
        end: undefined,
        code: undefined,
        packageName: undefined,
        pycode: undefined,
        isDisabled: undefined,
        overdueDate: undefined,
        minPrice: undefined,
        maxPrice: undefined,
        ptype: undefined
      },
      productPrince: 0,
      itemPrince: 0,
      TotalitemNo: 0, // 项目
      TotalitemNoPrice:0, // 项目价格
      TotalProductNo: 0, // 产品
      TotalProductNoPrice:0, //产品
      changeCloumns: [],
      changeDb: [],
      detaiColumns: [
        { title: '名称', dataIndex: 'itemName', key: 'name' },
        { title: '单位', dataIndex: 'packagePrice', key: 'packagePrice' },
        { title: '规格', dataIndex: 'itemUnit', key: 'itemUnit' },
        {
          title: '价格',
          dataIndex: 'price',
          key: 'price',
          customRender: (price) => {
            if (!price) {
              return '-'
            } else {
              return price.toFixed('2')
            }
          },
        },
        { title: '数量', dataIndex: 'useTimes', key: 'useTimes' },
        { title: '执行科室', dataIndex: 'twoDeptName', key: 'twoDeptName' },
      ],
      columnsSet: [
        { title: '名称', align: "center", dataIndex: 'itemName', key: 'itemName' },
        { title: '单位', align: "center", dataIndex: 'unit', key: 'unit' },
        {
          title: '原价',
          align: "center",
          dataIndex: 'originalPrice',
          key: 'originalPrice',
          scopedSlots: { customRender: 'originalPrice' },
          // customRender: (money) => {
          //   if (money == null) {
          //     return '-' 
          //   } else { 
          //     console.log(money)
          //     return money.toFixed('2')
          //   }
          // },
        },
        {
          title: '数量',
          align: "center",
          dataIndex: 'useTimes',
          key: 'useTimes',
          scopedSlots: { customRender: 'useTimes' }
          // customRender: (useTimes) => {
          //   if (!useTimes) {
          //     return '-'
          //   } else {
          //     return useTimes
          //   }
          // },
        },
        {
          title: '执行科室',
          align: "center",
          dataIndex: 'execDeptName',
          key: 'execDeptName',
          customRender: (ex) => {
            if (!ex) {
              return '-'
            } else {
              return ex
            }
          },
        },
        {
          title: '套餐价',
          align: "center",
          dataIndex: 'amt',
          key: 'amt',
          scopedSlots: { customRender: 'amt' }
          // customRender: (amt) => {
           
          //   return amt.toFixed('2')
            
          // },
        },
        // { title: '套餐价', dataIndex: 'amt', key: 'amt' },
        { title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' } },
      ],
      packageDetail: [],
      registDate: [],
      dateFormat: 'YYYY/MM/DD',
      detailed: [],
      tableType: [
        { id: 0, value: '项目', label: '1' },
        { id: 1, value: '产品', label: '2' },
      ],
      isType: [
        {
          id: 0,
          value: '当月套餐',
          label: '2',
        },
        {
          id: 1,
          value: '长期套餐',
          label: '1',
        },
      ],
      queryParam: {
        pageNum: 1,
        pageSize: 20,
        id: undefined,
      },
      isDisabled: 0,
      ShowPopover: false,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),

      visible: false,
      Title: '',
      data: [],
      columns,
      innerColumns,
      innerData,
      loading: false,
      ExpandedRowKeys: [],
      TotalPrice: 0,

      temporary: {
        isEx: false,
        record: {}
      },
      // 打开修改的滚动条
      addpackageLoading: false,
      // 展开的loading
      openLoading: false
       
    }
  },
  components: { SuperTable },
  mounted() {
    this.getList()
  },
  methods: {
    isNumber(value) {         //验证是否为数字
      console.log(value)
      var patrn = /^(-)?\d+(\.\d+)?$/;
      if (patrn.exec(value) == null || value == "") {
        return false
      } else {
        return true
      }
    },
    // 输入价格的事件
    minMoneyChange(val){
      console.log(val)
      this.searchDB.minPrice = Number(val) 
    },
    maxMoneyChange(val){
      console.log(val)
      this.searchDB.maxPrice = Number(val)
    },
    // 套餐价格
    textChange(value,row,index){  
      this.packageDetail[index].amt = value
      this.packageDetail = [...this.packageDetail]
    },
    // 数量
    textChange2(value,row,index){ 
      console.log(value) 
      this.packageDetail[index].useTimes = value
      this.packageDetail[index].amt =  this.packageDetail[index].originalPrice / row.times * value
      this.packageDetail = [...this.packageDetail]
    },
    // 点击分页
    typeChange(pagination) {

      console.log(pagination)
      this.typepagination.current = pagination.current
      if(this.name == ''){
        this.typeQueryParam.pageNum = pagination.current
        this.typeQueryParam.pageSize = pagination.pageSize 
        
        if(this.type == '1'){
          this.getType(true)
        }else if(this.type == '2'){
          this.getType(false)
        }
      }
      
    },

    // 查询
    send() {
      
      this.typepagination.current = 1
      if(this.name == ''){
        this.typeQueryParam.pageNum = 1
        this.typeQueryParam.pageSize = 10 
        if(this.type == '1'){
          this.getType(true)
        }else if(this.type == '2'){
          this.getType(false)
        }
        return false
      }
      this.detailLoading = true 
      if (this.type === '2') {
        searchType({ name: this.name, type: this.type }).then((res) => {
          if(res.code != 200){
            this.$message.error(res.msg || res.message)
            return false 
          }
          this.detailLoading = false
          for (var i = 0; i < res.rows.length; i++) {
            res.rows[i].useTimes = 1
            res.rows[i].money = res.rows[i].price
            res.rows[i].type = '2'
            // if (dept[i].id === res.rows[i].twoDeptId) {
            //   console.log(dept[i], res.rows[i])
            //   res.rows[i].ex = dept[i].name
            // }
          }
           
          this.detailed = res.rows
          this.detaiColumns = [
            {
              title: '名称',
              key: 'name',
              dataIndex: 'name',
              customRender: (name) => {
                if (!name) {
                  return '-'
                } else {
                  return name
                }
              },
            },
            {
              title: '单位',
              key: 'basicUnit',
              dataIndex: 'basicUnit',
              customRender: (basicUnit) => {
                if (!basicUnit) {
                  return '-'
                } else {
                  return basicUnit
                }
              },
            },
            {
              title: '数量',
              key: 'useTimes',
              dataIndex: 'useTimes',
              customRender: (times) => {
                if (!times) {
                  return '-'
                } else {
                  return times
                }
              },
            },
            {
              title: '原价',
              key: 'price',
              dataIndex: 'price',
              customRender: (money) => {
                if (money == null) {
                  return '-'
                } else {
                  return money.toFixed('2')
                }
              },
            },
            {
              title: '执行科室',
              key: 'execDeptName',
              dataIndex: 'execDeptName',
              customRender: (execDeptName) => {
                if (!execDeptName) {
                  return '-'
                } else {
                  return execDeptName
                }
              },
            },
            // {
            //   title: '套餐价',
            //   key: 'price',
            //   dataIndex: 'price',
            //   customRender: (price) => {
            //     if (!price) {
            //       return '-'
            //     } else {
            //       return price
            //     }
            //   },
            // },
          ]
          this.typepagination.total = Number(res.total)
        })
      } else if (this.type === '1') {
        searchType({ name: this.name, type: this.type }).then((res) => {
          if(res.code != 200){
            this.$message.error(res.msg || res.message)
            return false
          }
          for (var i = 0; i < res.rows.length; i++) { 
            res.rows[i].type = '1'
            // if (dept[i].id === res.rows[i].twoDeptId) {
            //   console.log(dept[i], res.rows[i])
            //   res.rows[i].ex = dept[i].name
            // }
          }
          this.detailLoading = false 
          this.detailed = res.rows
          this.detaiColumns = [
            { title: '名称', key: 'name', dataIndex: 'name' },
            { title: '单位', key: 'itemUnit', dataIndex: 'itemUnit' },
            { title: '数量', key: 'useTimes', dataIndex: 'useTimes' },
            {
              title: '原价',
              key: 'price',
              dataIndex: 'price',
              customRender: (price) => {
                if (price == null) {
                  return '-'
                } else {
                  return price.toFixed('2')
                }
              },
            },
            {
              title: '执行科室',
              key: 'execDeptName',
              dataIndex: 'execDeptName',
              customRender: (execDeptName) => {
                if (!execDeptName) {
                  return '-'
                } else {
                  return execDeptName
                }
              },
            },
            // {
            //   title: '套餐价',
            //   key: 'price',
            //   dataIndex: 'price',
            //   customRender: (price) => {
            //     if (!price) {
            //       return '-'
            //     } else {
            //       price
            //     }
            //   },
            // },
          ]
          this.typepagination.total = Number(res.total)
        })
      }
    },
    reset() {
      this.searchDB = {}
      this.day = []
      console.log(this.searchDB)
      this.searchDB = Object.assign({},this.searchDB)
    },
    search(type = 'search',num = '') {
      if(num == 'one'){
        this.searchDB.pageNum = 1
        this.searchDB.pageSize = 20
        this.queryParams.pageNum = 1
        this.queryParams.pageSize = 20
        this.pagination.current = 1
      }else{
        this.searchDB.pageNum = this.queryParams.pageNum
        this.searchDB.pageSize = this.queryParams.pageSize
      }
      if (this.day.length > 0) {
        this.searchDB.start = moment(this.day[0]).format('YYYY-MM-DD') + ' 00:00:00'
        this.searchDB.end = moment(this.day[1]).format('YYYY-MM-DD') + ' 23:59:59'
      } else {
        this.searchDB.start = ''
        this.searchDB.end = ''
      }
      

      this.loading = true
      search(Object.assign(this.searchDB)).then((res) => {
        if (res.code === 200) {
          this.loading = false
          console.log(this.pagination)
          this.pagination.type = type
          res.rows.forEach((item) => {
            item.isDisabled = item.isDisabled == '1' ? '未启用' : '已启用'
            item.overdueDate = item.overdueDate == '1' ? '未过期' : '已过期'
            item.tags = item.isDisabled
            item.subTags = item.overdueDate
          })

          this.data = res.rows
          //测试要求，要让人感觉到有刷新的感觉

          this.pagination.total = parseInt(res.total) || 0
        }
        console.log(res)
      })
    },
    moment,
    tests() {
      console.log('test')
    },
    getType(type) {
      this.type = ''
      this.detailLoading = true
      if (type) {
        this.type = '1'
        this.name = ''
        getItemDetailById(this.typeQueryParam).then((res) => {
          if(res.code != 200){
            return false
          }
          this.detailLoading = false
          for (var i = 0; i < res.rows.length; i++) {
            res.rows[i].price = res.rows[i].price
            res.rows[i].money = res.rows[i].price
            // if (dept[i].id === res.rows[i].twoDeptId) {
            //   console.log(dept[i], res.rows[i])
            //   res.rows[i].ex = dept[i].name
            // }
          }
          this.detailed = res.rows
          this.detaiColumns = [
            { title: '名称', key: 'name', dataIndex: 'name' },
            { title: '单位', key: 'itemUnit', dataIndex: 'itemUnit' },
            { title: '数量', key: 'useTimes', dataIndex: 'useTimes' },
            {
              title: '原价',
              key: 'money',
              dataIndex: 'money',
              customRender: (money) => {
                if (money == null) {
                  return '-'
                } else {
                  return money.toFixed('2')
                }
              },
            },
            {
              title: '执行科室',
              key: 'execDeptName',
              dataIndex: 'execDeptName',
              customRender: (execDeptName) => {
                if (!execDeptName) {
                  return '-'
                } else {
                  return execDeptName
                }
              },
            },
            // {
            //   title: '套餐价',
            //   key: 'price',
            //   dataIndex: 'price',
            //   customRender: (price) => {
            //     if (!price) {
            //       return '-'
            //     } else {
            //       price
            //     }
            //   },
            // },
          ]
          // const dept = sessionStorage.getItem('dept')
          // console.log(dept)
          

          console.log(res)
        })
      } else {
        this.type = '2'
        this.name = ''
        axios({
          url: `/product/getProductList`,
          method: 'get',
          params: this.typeQueryParam,
        }).then((res) => {
          if(res.code == 200){
           
            this.detailLoading = false
            res.rows.forEach((item) => {
              item.type = '2'
              item.times = '1'
              item.money = item.price
            })

            this.detailed = res.rows
            this.detaiColumns = [
              {
                title: '名称',
                key: 'name',
                dataIndex: 'name',
                customRender: (name) => {
                  if (!name) {
                    return '-'
                  } else {
                    return name
                  }
                },
              },
              {
                title: '单位',
                key: 'basicUnit',
                dataIndex: 'basicUnit',
                customRender: (basicUnit) => {
                  if (!basicUnit) {
                    return '-'
                  } else {
                    return basicUnit
                  }
                },
              },
              {
                title: '数量',
                key: 'useTimes',
                dataIndex: 'useTimes',
                customRender: (times) => {
                  if (!times) {
                    return '-'
                  } else {
                    return times
                  }
                },
              },
              {
                title: '原价',
                key: 'money',
                dataIndex: 'money',
                customRender: (money) => {
                  if (money == null) {
                    return '-'
                  } else {
                    return money.toFixed('2')
                  }
                },
              },
              {
                title: '执行科室',
                key: 'execDeptName',
                dataIndex: 'execDeptName',
                customRender: (execDeptName) => {
                  if (!execDeptName) {
                    return '-'
                  } else {
                    return execDeptName
                  }
                },
              },
              // {
              //   title: '套餐价',
              //   key: 'price',
              //   dataIndex: 'price',
              //   customRender: (price) => {
              //     if (!price) {
              //       return '-'
              //     } else {
              //       return price
              //     }
              //   },
              // },
            ]
            this.typepagination.total = Number(res.total)
            
            console.log(res)
          }
          
        })
      }
    },
    // 展开事件
    async ca(expanded, record) {
      this.queryParam.pageNum = 1 
       
      this.temporary.isEx = expanded
      this.temporary.record = record

      if (expanded && record) {
        this.openLoading = true
         
        this.queryParam.id = record.tbPackageId
        // const dept = await axios({
        //   url: '/common/dept/list',
        //   method: 'get',
        // })
        // window.sessionStorage.setItem('dept', JSON.stringify(dept.data))
        getPackageDetailList(Object.assign(this.queryParam)).then((res) => {
          if(res.code != 200){
            this.$message.error(res.message || res.msg)
            return false
          }
          this.openLoading = false 
          if (res.code.toString() === '200') {
            res.rows.forEach((item) => {
              if (item.unitPrice) {
                item.unitPrice = this.moneyChange(item.unitPrice)
              }

              item.abled = item.itemIsDisabled || item.productIsDisabled
              item.abled == '0' ? (item.abled = '已启用') : (item.abled = '未启用')

              if (item.type != null && item.type == '2') {
                item.unitPrice = item.productPrice
                item.totalPrice = item.productPrice
              }
            })
            console.log(res.total)
            if (Number(res.total) > 20) {
              console.log('触发')
              this.loadMore = true
            }else{
              this.loadMore = false
            }
            this.innerData = res.rows
            let target = document.getElementsByClassName('ant-table-expanded-row')
            for (var i = 0; i < target.length; i++) {
              target[i].childNodes[1].colSpan = 14
            }

            //经典！
          }
        })
        this.ExpandedRowKeys = []
        this.ExpandedRowKeys.push(record.tbPackageId)
        console.log(this.ExpandedRowKeys)
      } else {
        this.ExpandedRowKeys = []
      }
    },
    moneyChange(Num) {
      return Num.toFixed(2)
    },

    getList() {
      this.loading = true
      console.log(document.getElementById('innerTable'))
      getPackage(this.queryParams).then((res) => {
        if(res.code != 200){
          this.$message.error(res.message || res.msg)
          return false
        }
        this.loading = false
         
        res.rows.forEach((item) => { 
          item.isDisabled = item.isDisabled == '1' ? '未启用' : '已启用'
          item.overdueDate = item.overdueDate == '1' ? '未过期' : '已过期'
          item.tags = item.isDisabled
          item.subTags = item.overdueDate
          if (item.totalPrice) {
            item.totalPrice = this.moneyChange(item.totalPrice)
          }
          if (item.unitPrice) {
            item.unitPrice = this.moneyChange(item.unitPrice)
          }
          if (item.packagePrice) {
            item.packagePrice = this.moneyChange(item.packagePrice)
          }
        })
        this.data = res.rows

        // this.data = res.data
        this.pagination.total = parseInt(res.total) || 0
        console.log(res, '获取套餐列表')
      })
    },
    addNum(total, num) {
      return total + num
    },
    add(type, record) {
      
      console.log('修改？', type, record)
      this.visible = true
      if (type === '1') {
        console.log('新增')
        console.log(type)
        this.Rrecord.types = ''
        this.packageDetail = []
        this.TotalProject = '0'
        this.TotalPrice = '0'
        this.form.resetFields() //重置表单
        return
      }
      if (type === '2' && record.tbPackageId) {
        this.addpackageLoading = true
        console.log('修改')
        this.Rrecord = record
        this.Rrecord.types = '2'
        this.packageDetail = []
        editDetail({ id: record.tbPackageId }).then((res) => {
          if(res.code != 200){
            return false
          }
          this.addpackageLoading = false

          for (var i = 0; i < res.rows.length; i++) {
            if (res.rows[i].isDisabled && res.rows[i].isDisabled === '1') {
              res.rows[i].isDisabled = false
            } else {
              res.rows[i].isDisabled = true
            }

            if (res.rows[i].itemName || res.rows[i].packageName) {
              res.rows[i].itemName = res.rows[i].itemName
              res.rows[i].packageName = res.rows[i].packageName 
            }

            
          }

          this.form.setFieldsValue({
            packageName: res.rows[0].packageName,
            isDisabled: res.rows[0].isDisabled,
            remark: res.rows[0].remark,
            ptype: res.rows[0].ptype,
            registDate: [res.rows[0].beginDate, res.rows[0].endDate],
          })
          let detail = res.rows[0]
          detail.packageDetailList.map(item => {
            item.times = item.useTimes
          })
          this.packageDetail = detail.packageDetailList
          console.log(this.packageDetail)

          // 项目
          let newData1 = this.packageDetail.filter(elem => {
            return elem.type == 1
          })
          this.TotalitemNo = newData1.length 
          let sumCount = 0
          newData1.map(elem => {
            sumCount+=elem.amt 
          })
          this.TotalitemNoPrice = sumCount 
          // 产品
          let newData2 = this.packageDetail.filter(elem => {
            return elem.type == 2
          })
          this.TotalProductNo = newData2.length
          let sumCount2 = 0
          newData2.map(elem => {
            sumCount2+=elem.amt 
          })
          this.TotalProductNoPrice = sumCount2
        })
      }
    },
    handleTableChange(pagination) {
      console.log(pagination)
      this.queryParams.pageNum = pagination.current
      this.queryParams.pageSize = pagination.pageSize
      this.pagination.current = pagination.current
      this.queryParams = JSON.parse(JSON.stringify(this.queryParams))
      if (this.pagination.type !== 'search') {
        this.getList()
      } else {
        console.log('2')
        this.search()
      }
      
      
    },
    clicks(record, index) {
      return {
        on: {
          dblclick: (e) => {
            // 判断当前是否存在 存在就不添加进数组 
            let boolIF = this.packageDetail.find(elemt => { 
              return elemt.id == record.id || elemt.itemId == record.id
            }) 
            if(boolIF != undefined){ 
              this.$message.error('当前数据已存在')
              return false
            }

             
            // this.packageDetail.forEach((item) => {
            //   console.log(item)
            //   if (item.type === '2') {
            //     //type2是产品
            //     // item.execDept = item.achieveDept
            //     item.amt = Number(item.originalPrice * 1 || item.price * 1) 
            //     item.useTimes = 1
            //     item.itemName = item.name || item.itemName 
            //     item.itemId = item.id || item.itemId
            //     item.unit = item.basicUnit || item.unit 
            //     item.originalPrice = Number(item.originalPrice || item.price)
            //     item.ex = item.execDeptName
            //     item.type = '2'  
                 
            //   } else {
            //     item.type = '1'
            //     //type1是项目
            //     // item.execDept = ''
            //     item.amt = Number(item.originalPrice * 1 || item.price * 1)
            //     item.itemId = item.id || item.itemId
            //     item.itemName = item.name || item.itemName
            //     item.unit = item.basicUnit || item.unit
            //     item.times = item.useTimes 
            //     item.originalPrice = Number(item.originalPrice || item.price)
            //     item.ex = item.execDeptName 
            //   }
            // }) 

            if (record.type === '2') {
              console.log(record)
              //type2是产品
              // record.execDept = record.achieveDept
              record.amt = Number(record.originalPrice * 1 || record.price * 1) 
              record.useTimes = 1
              record.itemName = record.name || record.itemName 
              record.itemId = record.id || record.itemId
              record.unit = record.basicUnit || record.unit 
              record.originalPrice = Number(record.originalPrice || record.price)
              record.ex = record.execDeptName
              record.type = '2'  
              record.times = 1
                
            } else {
              record.type = '1'
              //type1是项目
              // record.execDept = ''
              record.amt = Number(record.originalPrice * 1 || record.price * 1)
              record.itemId = record.id || record.itemId
              record.itemName = record.name || record.itemName
              record.unit = record.basicUnit || record.unit
              record.times = record.useTimes 
              record.originalPrice = Number(record.originalPrice || record.price)
              record.ex = record.execDeptName 
            }
            console.log(record)
            this.packageDetail.push(record)
            
          },
        },
      }
    },

    hide() {
      this.ShowPopover = false
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
      this.form.resetFields()
    },
    handleOk(e) {
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        if (errors) {
          console.log('表单检验未通过111', errors, values)
          return
        }
        if (this.Rrecord.tbPackageId) {
          const time = values.registDate
          values.tbPackageId = this.Rrecord.tbPackageId
          if (values.isDisabled) {
            values.isDisabled = 0
          } else {
            values.isDisabled = 1
          }
          if (time && time.length > 0) {
            values.beginDate = moment(time[0]).format('YYYY-MM-DD')
            values.endDate = moment(time[1]).format('YYYY-MM-DD')
          }
          values.packageDetail = this.packageDetail
          console.log(values)
          editPackage(Object.assign(values)).then((res) => {
            if (res.code && res.code.toString() !== '200') return this.$message.error(res.msg || res.message)
            this.$message.success(res.msg || res.message)
            this.visible = false
            this.Rrecord = {} 
 
            // 暂存状态 修改之后展开
            this.ca(this.temporary.isEx, this.temporary.record)

            this.getList()
          })
          // //修改提交editPackage
        } else {
          console.log('新增')
          const time = values.registDate
          if (time && time.length > 0) {
            values.beginDate = moment(time[0]).format('YYYY-MM-DD')
            values.endDate = moment(time[1]).format('YYYY-MM-DD')
          }
          if (values.isDisabled) {
            values.isDisabled = 0
          } else {
            values.isDisabled = 1
          }
          values.packageDetail = this.packageDetail
          addPackage(Object.assign(values)).then((res) => {
             
            if(res.code === 200){
              this.$message.success(res.message)
              this.visible = false
              
              
              // 暂存状态 修改之后展开
              this.ca(this.temporary.isEx, this.temporary.record)


              this.getList()
            }else{
              this.$message.error(res.message)
            }
            
          })
          // //新增提交
        }
      })
    },
    handleChange(val) {
      console.log(val)
    },
    loadMores() {
      
      this.queryParam.pageNum += 1
      this.openLoading = true
      getPackageDetailList(Object.assign(this.queryParam)).then((res) => {
        if(res.code != 200){ 
          this.$message.error(res.message || res.msg)
          return false
        }
        this.openLoading = false
        res.rows.forEach((item) => {
          item.abled = item.itemIsDisabled || item.productIsDisabled
          item.abled == '0' ? (item.abled = '已启用') : (item.abled = '未启用') 
        })
         
        this.innerData = [...this.innerData,...res.rows]
        if (this.innerData.length.toString() === res.total.toString()) {
          this.loadMore = false
        }
      })
    },
    removeItem(record, index) {
      console.log(record, this.Rrecord, index)
      this.packageDetail.splice(index,1)

      // if (record && this.Rrecord.types === '2') {
      //   removeItem({ id: record.itemId, packageId: this.Rrecord.tbPackageId }).then((res) => {
      //     if (res.code === 200) {
      //       this.$message.success('操作成功')
      //       editDetail({ id: this.Rrecord.tbPackageId }).then((res) => {
      //         this.packageDetail = [...res.rows[0].packageDetailList]
      //       })
      //     } else {
      //       this.$message.error(res.message)
      //     }
      //   })
      // } else {
      //   this.packageDetail.splice(index, 1)
      // }
    },
  },
}
</script>